package leetcode.code1298;

import java.util.LinkedList;
import java.util.Queue;

public class Solution1 extends Solution1298 {

	@Override
	public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
		int boxNum = status.length;
		boolean[] key = new boolean[boxNum];// 持有的钥匙
		boolean[] closed = new boolean[boxNum];// 持有的关着的盒子
		Queue<Integer> q = new LinkedList<>();
		for (int cur : initialBoxes) {
			q.add(cur);
		}
		int ans = 0;
		while (!q.isEmpty()) {
			int curBox = q.poll();
			if (status[curBox] == 1 || key[curBox]) {
				for (int newBox : containedBoxes[curBox]) {// 新来的盒子
					q.add(newBox);
				}
				for (int newKey : keys[curBox]) {
					if (closed[newKey]) {
						q.add(newKey);
						closed[newKey] = false;// 同一个盒子的钥匙会出现多把，不讲武德
					}
					key[newKey] = true;
				}
				ans += candies[curBox];
			} else {
				closed[curBox] = true;// 同一个盒子的钥匙会出现多把，不讲武德
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		Solution1 so = new Solution1();
		so.debug1();
//		so.debug2();
//		so.debug3();
//		so.debug4();
//		so.debug5();
	}

}
